package com.liujie.app.controller;

import com.liujie.app.entity.AppInfo;
import com.liujie.app.entity.AppVersion;
import com.liujie.app.service.AppInfoService;
import com.liujie.app.service.AppVersionService;
import com.liujie.app.vo.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class AppVersionController {
    @Autowired

    AppVersionService appVersionService;
    @Autowired
    AppInfoService appInfoService;
    @PostMapping("/selVersion")
    public Result selVersion(Integer appid){
        List<AppVersion> list = appVersionService.getSelVersion(appid);
        return Result.success(list);
    }
    @PostMapping("/insertVersion")
    public Result insertVersion(AppVersion appVersion, MultipartFile file, HttpServletRequest request){
        if (file!=null && !file.isEmpty()){
            String realPath = request.getServletContext().getRealPath("upload/apk");
            String filename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(filename);
            if (file.getSize()>5140000){
                return Result.error("图片大于500kb");
            }else if (extension.equalsIgnoreCase("apk")){
                filename= UUID.randomUUID().toString().replace("-","")+"."+extension;
                File save=new File(realPath);
                if (!save.exists()){
                    save.mkdirs();
                }
                try {
                    file.transferTo(new File(realPath+File.separator+filename));
                    appVersion.setDownloadlink("/upload/apk/"+filename);
                } catch (IOException e) {
                    e.printStackTrace();
                    return Result.error("操作失败");
                }
            }else {
                return Result.error("文件格式不正确");
            }
        }else {
            return Result.error("文件必填");
        }

        appVersion.setCreatedby(2L);
        appVersion.setCreationdate(new Date());
        appVersionService.getInsert(appVersion);

        AppInfo appInfo=new AppInfo();
        appInfo.setId(appVersion.getAppid());
        appInfo.setStatus(1L);
        appInfo.setCreatedby(2L);
        appInfo.setVersionid(appVersion.getId());
        appInfo.setCreationdate(new Date());
        appInfoService.getInsertOrUpdate(appInfo);
        return  Result.success();
    }
}
